package com.bihu.bihudemo.controller.oos;

import com.bihu.bihudemo.result.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理图片上传的控制器
 */
@RestController
@RequestMapping("upload")
public class OosController {

    @Value("${xxh.uploadPath}")
    public String filePath;

    @Value("${fileAccePort}")
    public String serport;

    @Value("${xxh.serverbaseUrl}")
    public String serUrl;

    @PostMapping("/postImage")
    public Result handlerUpload(@RequestParam("file") MultipartFile file) {

        System.out.println(filePath);
        if (file.isEmpty()) {
            return Result.error("上传文件为空");
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 新文件名(避免重复名字)
        fileName = UUID.randomUUID() + suffixName;
        //图片的访问路径
        String imageurl = serUrl + ":" + serport + "/image/" + fileName;
        System.out.println(imageurl);


        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return Result.ok().put("url",imageurl);

        } catch (IOException e) {

            return Result.error("上传失败");
        }
    }
}
